<?php
namespace MyAdmin\Controller;

use Think\Controller;

class ShopsController extends CommonController
{

  public function __construct()
  {
    parent::__construct();
    $this->check_login();
  }

  public function index()
  {
    $page = I("page", 1);
    $page_size = I("page_size", 10);
    $model = M("shops");
    //查询
    $name = I("name");
    $phone = trim(I("phone"));

    $status = trim(I("status"));

    //上架
    $where = "s.app_id={$this->app_id}";
    if ($name) {//用户名
      $where .= " and s.name like '%".trim($name)."%'";
      $where_ar['name'] = $name;
      $this->assign("name", $name);
    }

    if ($phone) {//店铺号码
      $where .= " and s.phone like '%".trim($phone)."%'";
      $where_ar['phone'] = $phone;
      $this->assign("phone", $phone);
    }

    if ($status) {//状态
      $where .= " and s.status = ".trim($status)."";
      $where_ar['status'] = $status;
      $this->assign("status", $status);
    }

    $field = "s.*";
    $order = "s.id desc";
    $list = $model->alias("s")->field($field)->where($where)->order($order)->page($page.",".$page_size)->select();

    foreach ($list as $key => &$value) {
      $value['created_at'] = local_time($value['created_at']);
      $value['updated_at'] = local_time($value['updated_at']);

      switch ($value['status']) {
        case 1:
          $value['status_str'] = "开启";
          break;
        case 2:
          $value['status_str'] = "关闭";
          break;
        default:
          # code...
          break;
      }

      $value['alias_addr'] = sub_str($value['addr'], 10);
      $value['alias_memo'] = !$value['memo'] ? '' :sub_str($value['memo'], 10);
    }

    $num = $model->alias("s")->where($where)->count();

    $page_list = get_html_page_list($url_name, $list, $page, $page_size, $num, $where_ar);
    $this->assign("page_list", $page_list);

    $this->display();
  }

  //改变状态
  public function status()
  {
    $status = I("status", 2);
    $id = I("id", '');

    $data["status"] = $status;
    $data["updated_at"] = $this->current_time;

    $result = M("shops")->where("id=$id")->save($data);

    if($result){
      $this->success('操作成功', U('Shops/index'));
    }else{
      $this->error('操作失败');
    }
  }

  //改变状态
  public function free()
  {
    $id = I("id", '');

    $free_user = M("users")->where("shop_id=$id")->save(array('shop_id'=>NULL));

    $data["updated_at"] = $this->current_time;
    $data["phone"] = NULL;

    $result = M("shops")->where("id=$id")->save($data);

    if($result){
      $this->success('操作成功', U('Shops/index'));
    }else{
      $this->error('操作失败');
    }
  }

  //更新二维码
  public function update_wxacode()
  {
    $id = I("id", '');

    $img_url = get_shop_wxacode($id, $this->app_id);

    if ($img_url) {
      M('shops')->where("id=$id")->save(array('qrcode' => $img_url));

      $this->success('操作成功', U('Shops/index'));
    } else {
      $this->error('操作失败');
    }
  }

  public function create(){
    $this->display();
  }

  /**
   * [新增商户]
   * @return [type] [description]
   */
  public function save()
  {
    $model = M("shops");

    if (IS_AJAX || IS_POST) {
      $data = I('post.');
      $name = trim(I('post.name'));
      $phone = trim(I('post.phone'));

      if ($_FILES) {
        $files = file_upload($this->app_id);
        if ($files) {
          $img_url = $files[0];
        } else {
          $this->error('LOGO上传失败');
        }
      }

      //验证合法性
      if (!$name) {
        $this->error('店铺名不能为空');
      }

      //店名
      $shop = $model->where("name='$name' and app_id={$this->app_id}")->find();
      if ($shop) {
        $this->error('店铺名已存在');
      }

      $shop = $model->where("phone='$phone' and app_id={$this->app_id}")->find();
      if ($shop) {
        $this->error('店铺手机号已存在');
      }

      if (!preg_match("/^[+]?[0-9]{1,15}$/", $phone)) {
        $this->error('店铺手机号格式错误');
      }

      $data["created_at"] = $data["updated_at"] = $this->now_time;
      $data['logo'] = $img_url ? $img_url : '';
      $data['app_id'] = $this->app_id;
      $data['types'] = 2;
      $data['delivery_types'] = 2;

      if (M('Shops')->create($data)) {
        $result = M('Shops')->add();

        if ($result) {
          $data = [];
          $data['shop_id'] = $result;
          $data['created_at'] = $data['updated_at'] = $this->current_time;
          $data['name'] = '未分类';
          M('product_cates')->create($data);
          M('product_cates')->add();
        }

        $this->success('操作成功', U('Shops/index'));
      } else {
        $this->error('操作失败');
      }
    }


  }

  public function send_template_msg()
  {
    $id = I('id', 0);
    $status = I('status', 0);
    $audit_content = I('audit_content', '请使用申请手机号在我是商户登录，如有疑问请点击小程序联系我们！');

    $shop = M("shops")->where(array('id' => $id))->find();

    // $user = M('users')->where(array(shop_id => $id))->find();
    // if (! $user) {
    //     return_data('error', 'user.empty');
    // }

    $apply_form = M('apply_forms');
    $date = date('Y-m-d H:i:s', time());
    $apply_form->create(array('shop_id' => $id,
                  'status' => $status,
                  'audit_content' => $audit_content,
                  'created_at' => $date,
                  'updated_at' => $date));
    $apply_form->add();

    $shop_update = array('status' => $status,
                        'updated_at' => $this->now_time);

    if ($status == 1) {
      $img_url = get_shop_wxacode($id, $this->app_id);
      if($img_url) $shop_update['qrcode'] = $img_url;
    }

    M("shops")->where("id={$id}")->save($shop_update);

    $audit_status = 1 == $status ? '店铺审核已通过' : '店铺审核被拒绝';
    $app_info = $this->app_info;
    $params = array(
      'xcx_openid' => $shop['xcx_openid'],
      'template_id' => $app_info['shop_audit_template_id'],
      'form_id' => $shop['form_id'],
      'data' => array(
        'keyword1' => array('value' => $audit_status, 'color' => '#173177'),
        'keyword2' => array('value' => $date, 'color' => '#173177'),
        'keyword3' => array('value' => $audit_content, 'color' => '#173177'),
      ),
      'page' => 'pages/index/index'
    );

    $response = send_app_msg($params, $this->app_id);
    if (!$response) {
      return_data("error", "提示消息发送失败");
    } else {
      return_data("success", "提示消息发送成功");
    }
  }

  public function update()
  {
    $data = I('post.');
    $name = trim(I('post.name'));
    $phone = trim(I('post.phone'));
    $id = $data['id'];

    $shop = M("shops")->where(array('id' => $id))->find();

    if (!$shop) {
      $this->error('店铺不存在');
    }

    if (!$name) {
      $this->error('店铺名不能为空');
    }

    if ($shop['name'] != $name) {
      $name_check = M('shops')->where("name='$name'")->find();

      if ($name_check) {
        $this->error('店铺名已存在');
      }
    }

    if ($shop['phone'] != $phone) {
      $phone_check = M('shops')->where("phone='$phone'")->find();
      if ($phone_check) {
        $this->error('店铺手机号已存在');
      }
    }

    if (!preg_match("/^[+]?[0-9]{1,15}$/", $phone)) {
      $this->error('店铺手机号格式错误');
    }

    $data["updated_at"] = $this->now_time;
    $result = M('shops')->where(array('id' => $id))->save($data);

    if ($result) {
      $this->success('操作成功', U('Shops/index'));
    } else {
      $this->error('操作失败');
    }
  }

  public function edit()
  {
    $id = I('id', 0);
    $shop = M("shops")->where(array('id' => $id))->find();

    $this->assign("shop", $shop);
    $this->display();
  }
}
